package com.example.controller;

import com.graduation.dto.AssetLabelDO;
import com.graduation.mapper.AssetLabelMapper;
import com.graduation.pojo.*;
import com.graduation.pojo.AssetLabelQuery;
import com.graduation.pojo.AssetLabelRequest;
import com.graduation.vo.AssetLabelVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@WebException
@RequestMapping("/asset-label")
public class AssetLabelController extends BaseController<AssetLabelDO, AssetLabelVO> {

    @Resource
    private AssetLabelMapper assetLabelMapper;

    @ResponseBody
    @GetMapping("/get")
        public WebResult<AssetLabelVO> get(Integer id) {
        return new WebResult<>(getVoByDo(assetLabelMapper.selectById(id), AssetLabelVO.class));
    }

    @ResponseBody
    @PostMapping("/page")
    public WebResult<PageResult<AssetLabelVO>> page(AssetLabelQuery query) {
        PageResult<AssetLabelVO> result = new PageResult<>();
        result.setRowCount(assetLabelMapper.selectCount(query));
        result.setPageCount((result.getRowCount() - 1) / query.getPageSize() + 1);
        if (query.getPageNum() > result.getPageCount()) {
            query.setPageNum(result.getPageCount());
        }
        result.setPageNum(query.getPageNum());
        // 设置分页查询偏移量
        query.setLimit((query.getPageNum() - 1) * query.getPageSize());
        result.setEntityList(assetLabelMapper.selectList(query).stream()
                .map(e -> getVoByDo(e, AssetLabelVO.class))
                .collect(Collectors.toList()));
        return new WebResult<>(result);
    }

    @ResponseBody
    @PostMapping("/operate")
    public WebResult<?> operate(HttpServletRequest servletRequest, AssetLabelRequest request) {
        AssetLabelDO assetLabelDO = getDoByRequest(request, AssetLabelDO.class);
        if (Objects.isNull(assetLabelDO.getId())) {
            assetLabelDO.setCreateTime(LocalDateTime.now());
            assetLabelDO.setUpdateTime(LocalDateTime.now());
            assetLabelMapper.insert(assetLabelDO);
        } else {
            assetLabelDO.setUpdateTime(LocalDateTime.now());
            assetLabelMapper.updateById(assetLabelDO);
        }
        return WebResult.success();
    }

    @ResponseBody
    @DeleteMapping("/delete")
    public WebResult<?> delete(Integer id) {
        assetLabelMapper.deleteById(id);
        return WebResult.success();
    }

    @RequestMapping("/to-asset-label")
    public String toAssetLabel() {
        return "asset/assetLabelAdmin";
    }

    @RequestMapping("/to-operate")
    public String toOperate(Model model, Integer id) {
        model.addAttribute("id", id);
        return "asset/operateAssetLabel";
    }
}
